import json

from selenium import webdriver
from selenium.common.exceptions import TimeoutException, InvalidCookieDomainException
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait

# 请先下载Chrome浏览器以及对应版本的Chrome Driver
CHROME_DRIVER = 'D:\\chromedriver-win64\\chromedriver.exe'


def create_chrome_driver(*, headless=False):
    """创建浏览器对象"""
    options = webdriver.ChromeOptions()
    if headless:  # 不显示浏览器窗口
        options.add_argument('--headless')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 防反爬
    options.add_experimental_option('useAutomationExtension', False)  # 防反爬
    browser = webdriver.Chrome(executable_path=CHROME_DRIVER, options=options)
    browser.execute_cdp_cmd(  # 防反爬
        'Page.addScriptToEvaluateOnNewDocument',
        {'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'}
    )
    return browser


def add_cookies(browser, cookie_file):
    """向浏览器添加cookie"""
    browser.get('https://cqu.cqbys.com')
    with open(cookie_file, 'r') as file:
        cookies_list = json.load(file)
        for cookie_dict in cookies_list:
            try:
                browser.add_cookie(cookie_dict)
            except InvalidCookieDomainException as e:
                print(f'无法添加cookie {cookie_dict}！')


def login(browser, cookie_file):
    """登录，获取cookie"""
    browser.get('https://cqu.cqbys.com/user/login')
    try:
        WebDriverWait(browser, 300).until(expected_conditions.url_to_be('https://cqu.cqbys.com/home/index'))
        with open(cookie_file, 'w') as file:
            json.dump(browser.get_cookies(), file)
    except TimeoutException as e:
        print('登录超时！')
        raise
